<template>
  <view class="clock-calendar">
    <view class="calendar">
      <!-- 日历切换 -->
      <view class="calendar-switch">
        <view class="calendar-switch__left" @tap="leftShiftMonth">
          <image :lazy-load="true" :src="imgGather.ARROWS_LEFT" />
        </view>
        <view class="calendar-switch__date">{{ presentYear }}年{{ presentMonth }}月</view>
        <view class="calendar-switch__right" @tap="rightShiftMonth">
          <image :lazy-load="true" :src="imgGather.ARROWS_RIGHT" />
        </view>
      </view>

      <!-- 日历星期信息 -->
      <view class="calendar-weeks">
        <view v-for="item in weekList" :key="item">{{ item }}</view>
      </view>

      <!-- 日历 -->
      <view class="calendar-days">
        <view v-for="(item,index) in daysArr" :key="index" class="calendar-days__in-week">
          <view v-for="(day,dayIndex) in item" :key="dayIndex" :class="dayStyle(day,index,dayIndex)" class="calendar-days__day" @tap="chooseDate(day,index,dayIndex)">
            <text>{{ day.today ? '今' : day.days }}</text>
            <!-- 已打卡 -->
            <text v-if="day.clockDayStatus === clockInfo.HAS_CLOCK" class="calendar-days__day--pointer__normal" />
            <!-- 补卡 -->
            <text v-if="day.clockDayStatus === clockInfo.REISSUE_CLOCK" class="calendar-days__day--pointer__reissue" />
            <!-- 右标 -- 开始日期 -->
            <text v-if="day.startDate" class="calendar-days__day--bubble__start">始</text>
            <!-- 右标 -- 结束日期 -->
            <!-- <text v-if="day.endDate" class="calendar-days__day--bubble__end">终</text> -->
            <!-- 右标 -- 补卡日期 -->
            <text v-if="day.clockDayStatus === clockInfo.REISSUE_CLOCK" class="calendar-days__day--bubble__reissue">补</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 打卡信息 -->
    <view class="clock-info">
      <SpecialBox class="special-box" :width="366" :height="76" :offset-x="12" :offset-y="8" :radius="8" :bgc="'linear-gradient(180deg, #FFF6D1 0%, #FFEEA9 100%)'" :bc="'#CB9064'">
        <view class="clock-info__title">我的打卡</view>
      </SpecialBox>
      <view class="clock-info__list">
        <BorderBox v-for="(item, index) in clockLog" :key="index" :inside-padding="18" :bg-color="'#FFFBEA'" :bd-color="'#CB9064'">
          <view class="clock-info__list-item">
            <ClockItem :audio-index="index" :page-on-hide="pageOnHide" :show-teacher-comment="true" :-item-handle-click="toClockDetail" :item="item" @generateClockPoster="generateClockPoster" @giveLikeHandle="refreshData" />
          </view>
        </BorderBox>

        <view v-show="!clockLog.length" class="clock-info__default">
          <view>
            <image :lazy-load="true" :src="imgGather.DEFAULT_IMG" />
          </view>
          <view class="clock-info__default--tip">今日还未打卡哦～</view>
          <view class="clock-info__default--btn" @tap="toClockIn">去打卡</view>
        </view>
      </view>
    </view>
    <!-- 分享图片 -->
    <ClockSign :show.sync="showShare" :theme-id="clockSignInfo.themeId" :student-id="clockSignInfo.studentId" :uuid="clockSignInfo.uuid" />
  </view>
</template>

<script>
import "./index.scss"
import { Component, Vue } from "vue-property-decorator"
import { clockCalendar, myClockLog } from "_api/clock-calendar"
import SpecialBox from "../../components/special-box/index.vue"
import ClockItem from "../../components/clock-item/index.vue"
import {
  DEFAULT_IMG,
  ARROWS_LEFT,
  ARROWS_RIGHT,
  HAS_CLOCK,
  REISSUE_CLOCK,
  CURRENT_DAY,
} from "@/config/clock-calendar"
import ClockSign from "@/components/generate-image"
import BorderBox from "_c/border-box/index"
import moment from "moment"
import Taro from "@tarojs/taro"
moment.suppressDeprecationWarnings = true

export default {
  components: { SpecialBox, ClockItem, BorderBox, ClockSign },
  data () {
    return {
      /* 星期信息 */
      weekList: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      /* 图片信息 */
      imgGather: {
        /* 今日未打卡缺省图片 */
        DEFAULT_IMG,
        /* 左箭头图片 */
        ARROWS_LEFT,
        /* 右箭头图片 */
        ARROWS_RIGHT,
      },
      /* 日期数组 */
      daysArr: [],
      /* 当前年份 */
      presentYear: Number(moment().format("YYYY")),
      /* 当前月份 */
      presentMonth: Number(moment().format("M")),
      /* 月份切换loading */
      shiftLoading: false,
      /* 学生打卡信息数组 */
      clockLog: [],
      /* 活动日期数据 */
      activeDays: {},
      /* 打卡状态标识集 */
      clockInfo: {
        /* 已打卡 */
        HAS_CLOCK,
        /* 补卡 */
        REISSUE_CLOCK,
      },
      /* show打卡海报 */
      showShare: false,
      /* 打卡海报id */
      themeId: 0,
      /* 今日日期id */
      currentDateId: -1,
      /* 选择的对应打卡日期 --id */
      clockDateId: -1,
      /*  */
      clockDateIndex: "",
      /* 日期对应打卡数据loading */
      clockDateLoading: false,
      /* 打卡日签信息 */
      clockSignInfo: {
        studentId: "",
        uuid: "",
        themeId: "",
      },
      /* 打卡错误状态 */
      errorStatus: "",
      pageOnHide: false,
      /* 首次生成日历 */
      firstCreate: true,
    }
  },
  computed: {
    /* 活动id */
    activityId () {
      return this.getParams.id
    },

    /* 选择的日期是否是当日日期 */
    isCurrentDate () {
      return this.currentDateId === this.clockDateId
    },
  },
  onHide () {
    this.pageOnHide = !this.pageOnHide
  },
  onShow () {
    !this.firstCreate && this.getMyClockLog()
  },


  /* ----------- */
  onLoad () {
    this.getClockCalendar()
  },
  methods: {
    /* 跳转到打卡详情 */
    toClockDetail ({
      student_clock_info: { id: clockId },
      student_base_info: { id: studentId },
    }) {
      Taro.navigateTo({
        url: `/pages/clock-detail/index?clock_id=${clockId}&student_id=${studentId}`,
      })
    },

    /* 生成打卡海报 */
    generateClockPoster (item) {
      this.showShare = true
      this.clockSignInfo = {
        studentId: item.student_base_info.id,
        uuid: item.student_clock_info.id,
        themeId: item.student_base_info.theme_id,
      }
    },
    /* 刷新数据 */
    refreshData (data) {
      /* data && this.getMyClockLog(); */
    },
    /* 去打卡 */
    toClockIn () {
      /* 今天没有可以打卡的主题详情 */
      if (!this.errorStatus) {
        Taro.showToast({
          title: "暂无可打卡主题，请稍后重试",
          icon: "none",
        })
        return
      }
      /* 如果今日没有配置主题详情-跳转到限时活动页面 */
      console.log(this.currentDateId, !this.currentDateId)
      if (this.currentDateId === -1) {
        Taro.navigateBack({ delta: 1 })
        /* Taro.navigateTo({
        url: `/pages/activity-detail/index?id=${this.activityId}`,
      }); */
        return
      }
      Taro.navigateTo({
        url: `/pages/theme-detail/index?id=${this.currentDateId}`,
      })
    },
    /* 点击对应日期 */
    chooseDate (item, index, dayIndex) {
      let { themeId, today, notInActivity, disable, moment } = item
      console.log(item, notInActivity, disable)
      if (notInActivity || disable) return
      console.log(themeId)
      this.clockDateId = themeId
      this.clockDateIndex = moment
      this.getMyClockLog(today)
    },
    /* 获取打卡数据 */
    async getMyClockLog (is_today) {
      if (this.clockDateLoading) return
      this.clockDateLoading = true
      const { data } = await myClockLog({ theme_id: this.clockDateId }).catch(
        (err) => {
          !is_today &&
            Taro.showToast({ title: err.message || '此日未打卡哦～', icon: "none" })
          return { data: null }
        }
      )
      /* 选择日期非今日且没有数据时 toast不改变数据 */
      data && (this.clockLog = [data])

      if (is_today && !data) {
        this.clockLog = []
      }
      this.clockDateLoading = false
    },
    /* 获取打卡日历状态信息 */
    async getClockCalendar (params={}) {
      const { not_request } = params
      const { data } = await clockCalendar({ id: this.activityId })

      data.theme_item = data.theme_item.reduce((all, item) => {
        /* 找出今日id */
        if (~~item.is_today) {
          console.log(item, "itemitemitem")
          this.clockDateId = ~~item.id
          this.currentDateId = ~~item.id
          this.errorStatus = item.theme_status
        }
        return { ...all, [item.date]: item }
      }, {})
      this.activeDays = data
      !not_request && this.getMyClockLog(true)
      console.time()
      this.monthDay(this.presentYear, this.presentMonth)
      console.timeEnd()
    },

    /* 生成日期class */
    dayStyle (item, index, dayIndex) {
      return {
        /* 今天 */
        "calendar-days__day--today": item.today,
        /* 不在本月的时间 */
        "calendar-days__day--past-time": item.disable || item.notInActivity,
        "calendar-days__day--choosed": this.clockDateIndex === item.moment
      }
    },
    /* 左移月份 */
    leftShiftMonth () {
      if (this.presentMonth === 1) {
        this.presentYear--
        this.presentMonth = 12
      } else {
        this.presentMonth--
      }
      this.getClockCalendar({ not_request: true })
    },
    /* 右移动月份 */
    rightShiftMonth () {
      if (this.presentMonth === 12) {
        this.presentYear++
        this.presentMonth = 1
      } else {
        this.presentMonth++
      }
      this.getClockCalendar({ not_request: true })
      /* clockCalendar() */
    },
    /* 生成月份信息 */
    monthDay (year, month) {
      if (this.shiftLoading) true
      this.shiftLoading = true
      let format = null
      let date = moment(`${year}/${month}/1`).startOf("month")
      let toDate = moment(`${year}/${month}/1`).endOf("month")
      let _date = moment(date, format)
      let _toDate = moment(toDate, format)
      const _cuurentTime = moment()
        .startOf("day")
        .format("x") /* 今日0时时间戳 */
      let daysArr = [] //日历数组
      const currentOne = _date.startOf("month") //开始月1号
      const currentWeekday = currentOne.weekday() //开始月1日为星期几
      const endWeekday = _toDate.weekday() //结束日为星期几
      const startTime = currentOne.subtract(currentWeekday - 1, "days") //开始时间
      const endTime = _toDate.add(6 - endWeekday, "days") //结束时间
      const diffDay = endTime.diff(startTime, "days") //相差
      //天数一维数组
      let index = startTime
      console.log(_cuurentTime, "_cuurentTime")
      for (let i = 0; i <= diffDay + 1; i += 1) {
        date = moment(date, format)
        toDate = moment(toDate, format)
        const disable =
          date.isAfter(index) || toDate.isBefore(index) ? true : false
        const days = index.format("D")
        const month = index.format("MM")
        const year = index.format("YYYY")
        /* 活动开始日期 */
        const startDate =
          !disable &&
          this.activeDays.start_date ===
          `${year}-${month}-${index.format("DD")}`

        /* 活动结束时间 */
        const endDate =
          !disable &&
          this.activeDays.end_date === `${year}-${month}-${index.format("DD")}`
        /* 是否在活动日期内 */

        const notInActivity = Number(moment(`${year}/${month}/${index.format("DD")}`).format("x")) > Number(moment(this.activeDays.end_date.replace(/\-/ig, '/')).format("x"))
          || Number(moment(`${year}/${month}/${index.format("DD")}`).format("x")) < Number(moment(this.activeDays.start_date.replace(/\-/ig, '/')).format("x"))
        /* 打卡日期状态 */
        const today = Number(index.format("x")) === Number(_cuurentTime)
        this.firstCreate && today && (this.clockDateIndex = index.format(format))

        const clockDayStatus = this.activeDays.theme_item[
          `${year}-${month}-${index.format("DD")}`
        ]
        daysArr.push({
          themeId: clockDayStatus ? Number(clockDayStatus.id) : 0,
          startDate,
          endDate,
          moment: index.format(format),
          disable,
          days,
          notInActivity,
          clockDayStatus:
            clockDayStatus && !disable ? Number(clockDayStatus.status) : 0,
          pastTime: Number(index.format("x")) <= Number(_cuurentTime),
          today: Number(index.format("x")) === Number(_cuurentTime),
          year,
          month,
        })
        index.add(1, "days")
      }
      //天数二维数组
      let arr = Array.from(new Array(Math.ceil(daysArr.length / 7)), (v) => [])
      for (let i = 0, len = daysArr.length; i < len; i += 1) {
        arr[Math.floor(i / 7)].push(daysArr[i])
      }
      daysArr = arr
      this.daysArr = arr
      console.log(this.daysArr)
      this.firstCreate = false
      this.shiftLoading = false
    },
  },
};
</script>